//
//  NSString+Verifying.m
//  FashionTech
//
//  Created by JackieYip on 16/5/13.
//  Copyright © 2016年 mondial-d. All rights reserved.
//

#import "NSString+Verifying.h"

NSString * const kChinaCode = @"+86";
NSString * const kHongKongCode = @"+852";
NSString * const kMaCaoCode = @"+853";
NSString * const kTaiwanCode = @"+886";

@implementation NSString (Verifying)
- (BOOL)verifyWithPattern:(NSString *)pattern
{
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", pattern];
    return [predicate evaluateWithObject:self];
}

- (BOOL)isValidUserName {
//    return [self verifyWithPattern:@"^[A-Za-z\u4e00-\u9fa5]{2,15}$"];
    return [self verifyWithPattern:@"^.{2,15}$"];
}

- (BOOL)isValidPhoneCN { // 中国大陆：11位数字，检查手机有效性
    return [self verifyWithPattern:@"^1[3578][0-9]{9}$"];
}

- (BOOL)isValidPhoneHK { // 中国香港：8位数字
    return [self verifyWithPattern:@"[0-9]{8}"];
}

- (BOOL)isValidPhoneMacao { // 中国澳门：8位数字
    return [self verifyWithPattern:@"[0-9]{8}"];
}

- (BOOL)isValidPhoneTaiwan { // 中国台湾：10位数字
    return [self verifyWithPattern:@"[0-9]{10}"];
}

- (BOOL)isValidPhoneWithAreaCode:(NSString *)areaCode
{
    if (
        // 中国大陆
        ([areaCode isEqualToString:kChinaCode] &&
         ![self isValidPhoneCN]) ||
        // 香港
        ([areaCode isEqualToString:kHongKongCode] &&
         ![self isValidPhoneHK]) ||
        // 澳门
        ([areaCode isEqualToString:kMaCaoCode] &&
         ![self isValidPhoneMacao]) ||
        // 台湾
        ([areaCode isEqualToString:kTaiwanCode] &&
         ![self isValidPhoneTaiwan]))
    {
        return NO;
    }
    else
        return YES;
}

- (BOOL)isValidId {
    NSString *value = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSUInteger length = 0;
    if (!value) {
        return NO;
    }
    else {
        length = value.length;
        
        if (length != 15 && length != 18) {
            return NO;
        }
    }
    // 省份代码
    NSArray *areasArray = @[@"11", @"12", @"13", @"14", @"15", @"21", @"22", @"23", @"31", @"32", @"33", @"34", @"35", @"36", @"37",@"41", @"42", @"43", @"44", @"45", @"46", @"50", @"51", @"52", @"53", @"54", @"61", @"62", @"63", @"64", @"65", @"71", @"81", @"82", @"91"];
    
    NSString *valueStart2 = [value substringToIndex:2];
    BOOL areaFlag = NO;
    for (NSString *areaCode in areasArray) {
        if ([areaCode isEqualToString:valueStart2]) {
            areaFlag = YES;
            break;
        }
    }
    
    if (!areaFlag) {
        return NO;
    }
    
    
    NSRegularExpression *regularExpression;
    NSUInteger numberofMatch;
    
    int year = 0;
    switch (length) {
        case 15:
            year = [value substringWithRange:NSMakeRange(6,2)].intValue + 1900;
            if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }else {
                regularExpression = [[NSRegularExpression alloc] initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                                                         options:NSRegularExpressionCaseInsensitive
                                                                           error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if (numberofMatch > 0) {
                return YES;
            } else {
                return NO;
            }
        case 18:
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            } else {
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                                                        options:NSRegularExpressionCaseInsensitive
                                                                          error:nil];//测试出生日期的合法性
            }
            numberofMatch = [regularExpression numberOfMatchesInString:value
                                                               options:NSMatchingReportProgress
                                                                 range:NSMakeRange(0, value.length)];
            
            if(numberofMatch > 0) {
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) * 7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) * 9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) * 10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) * 5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) * 8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) * 4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) * 2 + [value substringWithRange:NSMakeRange(7,1)].intValue * 1 + [value substringWithRange:NSMakeRange(8,1)].intValue * 6 + [value substringWithRange:NSMakeRange(9,1)].intValue * 3;
                int Y = S % 11;
                NSString *M = @"F";
                NSString *JYM = @"10X98765432";
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    return YES;// 检测ID的校验位
                }else {
                    return NO;
                }
            }else {
                return NO;
            }
        default:
            return NO;
    }
}

- (BOOL)isValidEmail {
    return [self verifyWithPattern:@"^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$"];
}

- (BOOL)isValidRemark {
    return [self verifyWithPattern:@"^.{0,20}$"];
}

- (BOOL)isValidPassword { // 6~20位，限字母、数字、下划线、区分大小写、不允许空格
    return [self verifyWithPattern:@"^[A-Za-z0-9_]{6,20}$"];
}

- (BOOL)isValidACode { // 4~10位，限字母、数字
    return [self verifyWithPattern:@"^[A-Za-z0-9]{4,10}$"];
}

- (BOOL)isValidCCode { // 任意位，限字母、数字
    return [self verifyWithPattern:@"^[A-Za-z0-9]*"];
}

- (BOOL)isValidICode { // 6位，限字母、数字
    return [self verifyWithPattern:@"^[A-Za-z0-9]{6}$"];
}

- (BOOL)isValidVCode { // 4位数字（登录注册验证码）
    return [self verifyWithPattern:@"^[0-9]{4}$"];
}

- (BOOL)isValidAddress { // 5-60位
    return [self verifyWithPattern:@"^.{5,60}$"];
}

- (BOOL)isValidCompany { // 30个字以内，限汉字、字母、数字
    return [self verifyWithPattern:@"^[A-Za-z0-9\u4e00-\u9fa5]{0,30}$"];
}

- (BOOL)isValidReviewComments { // 140位以内，限汉字、数字、符号
    return [self verifyWithPattern:@"^.{0,140}$"];
}

- (BOOL)isValidSpecs {  // 20位英文字符数字
    return [self verifyWithPattern:@"^[0-9\\x00-\\xff]{0,20}$"];
}

- (BOOL)isValidPrice {  // 4位整数，2位小数
    return [self verifyWithPattern:@"^[0-9]{0,4}\\.?[0-9]{0,2}$"];
}

- (BOOL)isValidCarriage {   // 4位整数，2位小数
    return [self verifyWithPattern:@"^[0-9]{0,4}\\.?[0-9]{0,2}$"];
}

- (BOOL)isValidTotalAmount {    // 11位整数，2位小数
    return [self verifyWithPattern:@"^[0-9]{0,11}\\.?[0-9]{0,2}$"];
}

- (BOOL)isValidQuantity {   // 3位整数
    return [self verifyWithPattern:@"^[0-9]{0,3}$"];
}

- (BOOL)isValidTons {   // 4位整数，3位小数
    return [self verifyWithPattern:@"^[0-9]{1,4}\\.?[0-9]{0,3}$"];
}

- (BOOL)isValidWeight {    // 7位整数，3位小数
    return [self verifyWithPattern:@"^[0-9]{1,7}\\.?[0-9]{0,3}$"];
}

- (BOOL)isValidFavoriteProduct {
    return [self verifyWithPattern:@"^[A-Za-z\u4e00-\u9fa5]{1,20}$"];
}

- (BOOL)isValidNumber {     // 任意个数字
    return [self verifyWithPattern:@"[0-9]*"];
}

- (BOOL)isValidPhoneIncludeAreaCode {
    NSString *phoneWithAreaCode = [self copy];
    phoneWithAreaCode = [phoneWithAreaCode stringByReplacingOccurrencesOfString:@" " withString:@""];
    return [phoneWithAreaCode verifyWithPattern:@"[0-9+-]*"];
}

- (BOOL)isValidDecimal {    // 任意个数字、一个或零个.
    return [self verifyWithPattern:@"[0-9]*\\.?[0-9]*"];
}

- (BOOL)isValidURL {        // URL
    return [self verifyWithPattern:@"[a-zA-Z]+://[^\\s]*"];
}

- (BOOL)isValidWWWURL {
    return [self verifyWithPattern:@"[a-zA-Z]+://[wW]{3}[^\\s]*"];
}

- (NSString *)stringFormatForPreviousZero {     // 将输入为 00.0和00 的情况 转化为 0.0和0，过滤掉前缀无效0
    NSUInteger dotLength = [self rangeOfString:@"."].length;
    if ([self doubleValue] >= 1.0) {                                                      // 值>=1.0
        NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"[1-9][0-9]*.?[0-9]*" options:0 error:nil];
        NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
        NSString *subString = [NSString stringWithString:self];
        for (NSTextCheckingResult *result in results) {
            subString = [self substringWithRange:result.range];
        }
        return subString;
    }
    else if ([self doubleValue] != 0.0 || dotLength > 0) {                                 // 0<值<1 或 值 == 0.0（带小数点）
        NSString *subString = [NSString stringWithString:self];
        // . 变成 0.
        if ([self isEqualToString:@"."]) {
            subString = @"0.";
        }
        else {
            NSRegularExpression *regex = [[NSRegularExpression alloc] initWithPattern:@"\\.[0-9]*" options:0 error:nil];
            NSArray *results = [regex matchesInString:self options:0 range:NSMakeRange(0, self.length)];
            for (NSTextCheckingResult *result in results) {
                subString = [self substringWithRange:NSMakeRange(result.range.location - 1, result.range.length + 1)];
            }
        }
        return subString;
    }
    else if (![self isEqualToString:@""] && [self doubleValue] == 0.0)  // 值 == 0（无小数点）
        return @"0";
    else
        return self;
}
@end
